<template>
	<view class="content" :class="isfull?'fixed':''"  ref="parentContainer">
		<NavBar :title="title" :autoBack="false" id="nav">
			<template #left>
				<view class="navbar-left center" @click="goBack">
					<u-icon name="arrow-left" color="#007aff" size="34"></u-icon>
				</view>
			</template>
		</NavBar>
		<view class="main">
			<view class="videobox">
				<view class="time" :class="isfull?'timefull':''">{{ currentTime }}</view>
				<!-- <jessibucaPlayer ref="jessibuca" @scrollTo="scrollChild" @screenhot="saveScreen"
					:visible.sync="showVideoDialog" :videoUrl="videoUrl" :error="videoError" :message="videoError"
					height="100px" :hasAudio="hasAudio" fluent autoplay live></jessibucaPlayer> -->
					
					<synewjessibuca v-if="showVideo"  :url="videoUrl" :isAuto="true" :isNotMute="ismuted"  :screensJosn='screensJosn'  @printscreen="saveScreen"
						@openFulls="changeFulls"
					>
					    <view>
					    </view>
					</synewjessibuca>
					
			</view>
			<view class="actionbox">
				<view class="flex widths box">
					<view class="dirCloumn item" @click="openShowStarttime">
						<view class="center picbox">
							<u-image width="44rpx" height="44rpx" mode="aspectFit"
								src="../../static/img01.png"></u-image>
						</view>
						<view class="f28 txt">搜索</view>
					</view>
					<view class="dirCloumn item" @click="toPics">
						<view class="center picbox">
							<u-image width="44rpx" height="44rpx" mode="aspectFit"
								src="../../static/img02.png"></u-image>
						</view>
						<view class="f28 txt">畫面快照</view>
					</view>
					<view class="dirCloumn item" @click="toPlayback">
						<view class="center picbox">
							<u-image width="44rpx" height="44rpx" mode="aspectFit"
								src="../../static/img03.png"></u-image>
						</view>
						<view class="f28 txt">回放</view>
					</view>
				</view>

			</view>

			<view class="mt-30 userlist">
				<view class="widths">
					<view class="flex titbox">
						<view class="title">用戶</view>
						<view class="subtitle" v-if="curUserident == 1" :class="isaction?'on':''" @click="openAuthor">授權
						</view>
					</view>
					<ZPaging ref="paging" :fixed="false" :auto="false" :auto-show-system-loading="true"
						:use-page-scroll="true" v-model="userlist" loading-more-no-more-text="沒有更多了"
						loading-more-default-text="點擊加載更多" loading-more-loading-text="正在加載..."
						loading-more-fail-text="加載失敗,點擊重新加載" empty-view-text="沒有數據哦~" refresher-default-text="繼續下拉刷新"
						refresher-pulling-text="鬆開立即刷新" refresher-refreshing-text="正在刷新" empty-view-reload-text="重新加載"
						empty-view-error-text="加載失敗" @query="queryList">
						<view class="useritembox">
							<view class=" flex item" v-for="(v,k) in userlist" :key="k">
								<view class="left">
									<view class="flex namebox">
										<view class="mr-8  name">{{v.nickname}}</view>
										<view class="c999 f26 auth">{{getAuthTxt(v.ident)}}</view>
									</view>
									<view class="c666 company">企業: {{v.company_name}}</view>
								</view>
								<view class="right">
									<view class="checkbox" v-if="isaction">
										<u-checkbox v-model="v.ischecked"></u-checkbox>
									</view>
									<view class="txt" v-else :class="v.isbind?'c007aff':'c999'">{{v.isbind?'已綁定':'未綁定'}}
									</view>
								</view>
							</view>
						</view>
					</ZPaging>


				</view>
			</view>

		</view>
		<Tabar></Tabar>
		<view class="btnbox" v-if="isaction" @click="toUpdateAuth">
			<view class="btn">確認授權</view>
		</view>
		<u-picker mode="time" v-model="showTime" :default-time="timePickerDefault" :params="params" confirm-text="確認"
			cancel-text="取消" title="開始時間" @confirm="confirmDate"></u-picker>
		<u-picker mode="time" v-model="showEndTime" :default-time="timePickerDefault" :params="params" confirm-text="確認"
			cancel-text="取消" title="结束時間" @confirm="confirmDateEnd"></u-picker>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex";
	import Tabar from "@/component/HomeTab"
	import NavBar from "@/component/NavBar"
	import jessibucaPlayer from "@/component/jessibuca.vue"
	import ZPaging from "@/node_modules/z-paging/components/z-paging/z-paging.vue"
	import synewjessibuca from "@/uni_modules/sy-new-jessibuca/components/sy-new-jessibuca/sy-new-jessibuca.vue"
	import {
		baseUrl,
		videoImgBaseUrl
	} from "@/api/url.js"
	import {
		getVideoUrl,
		getCaseUserlist,
		getCaseUserIdent,
		updateAuth,
		saveVideoPic
	} from "@/api/apis.js"
	var passwordRegex = /^[a-zA-Z0-9_]{6,16}$/;
	export default {
		components: {
			Tabar,
			NavBar,
			ZPaging,
			jessibucaPlayer,
			synewjessibuca
		},
		data() {
			return {
				action: baseUrl + '/api/apict/uploadfile',
				videoImgBaseUrl: videoImgBaseUrl,
				title: "實時畫面",
				list: [],
				templist: [],
				curid: 0,
				status:false,
				playInfo: {
					fmp4: "",
				},
				videoObj: null,
				currentTime: "",
				isaction: false,
				caseid: 0,
				userlist: [],
				curUserident: 0,
				showTime: false,
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true,
					timestamp: true,
				},
				timePickerDefault: "",
				startTime: "",
				endTime: "",
				showEndTime: false,
				ismuted: true,
				isfull: false,
				showLoading: false,
				videoHeight: 0,
				videoPlayer: null,
				isPlaying: false,
				showVideoDialog: false,
				showVideo:false,
				// videoUrl: "ws://211.22.123.64:80/rtp/34020000001110005555_34020000001110005555.live.flv",
				videoUrl:"",
				videoError: "error",
				hasAudio: true,
				screensJosn:{
					name:'pic',
					format:'png',
					quality:1,
					type:"base64"
				}

			}
		},
		// onReady() {
		// this.initVideo()
		// },
		created() {
			setInterval(() => {
				const date = new Date();
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			}, 1000);
		},
		onShow() {
			this.setTabList(uni.getStorageSync("bindevice"))
			const {
				status,
				id,
				caseid
			} = this.$Route.query
			console.log('id',id)
			if (id && caseid) {
				this.curid = id
				this.caseid = caseid
				this.status = status
				uni.setStorageSync("vid", id)
				uni.setStorageSync("caseid", caseid)
				uni.setStorageSync("videostatus", status)

				// this.init()
			} else {
				if (uni.getStorageSync("vid") && uni.getStorageSync("vid") != 0) {
					this.curid = uni.getStorageSync("vid")
					this.caseid = uni.getStorageSync("caseid")
					this.status = uni.getStorageSync("videostatus")
					// this.init()
				} else {
					this.goBack()
				}
			}
			this.$nextTick(() => {

				if (uni.getStorageSync("islogin")) {
					this.ident = parseInt(uni.getStorageSync("ident"))
					if (uni.getStorageSync('name')) {
						this.changeUserName(uni.getStorageSync('name'))
					}
				}
			})
		},
		onLoad() {

		},
		mounted() {

			this.$nextTick(() => {
				this.videoObj = this.$refs.videoPlayer;

				this.setBtnBoxHeight()
				this.init();
			});
		},
		computed: {
			...mapState(["userinfo"]),
		},
		methods: {
			...mapMutations(['chageUserPageType', 'chageUserPageId', 'changeUserIdent', 'changeUserName', 'setTabList']),
			initVideo() {
				let video = document.createElement('video');
				video.id = 'video';
				// video.style = 'width: 100%; height: 100%;';
				// video.controls = true;
				video.preload = "auto"
				video.setAttribute('playsinline', true) //IOS微信浏览器支持小窗内播放
				video.setAttribute('webkit-playsinline', true) //这个bai属性是ios 10中设置可以让视频在小du窗内播放，也就是不是全zhi屏播放的video标签的一个属性
				video.setAttribute('x5-video-player-type', 'h5') //安卓 声明启用同层H5播放器 可以在video上面加东西
				let source = document.createElement('source');
				source.src = 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8';
				video.appendChild(source);                                    
				// return
				this.$refs.videos.appendChild(video);
				let that = this;
				let player = this.$video(
					'video', {
						autoDisable: true,
						preload: 'none', //auto - 当页面加载后载入整个视频 meta - 当页面加载后只载入元数据 none - 当页面加载后不载入视频
						language: 'zh-CN',
						fluid: true, // 自适应宽高
						muted: false, //  是否静音
						aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
						controls: true, //是否拥有控制条 【默认true】,如果设为false ,那么只能通过api进行控制了。也就是说界面上不会出现任何控制按钮
						autoplay: false, //如果true,浏览器准备好时开始回放。 autoplay: "muted", // //自动播放属性,muted:静音播放
						loop: true, // 导致视频一结束就重新开始。 视频播放结束后，是否循环播放
						controlBar: {
							volumePanel: { //声音样式
								inline: true // 不使用水平方式
							},
							timeDivider: true, // 时间分割线
							durationDisplay: true, // 总时间
							progressControl: true, // 进度条
							remainingTimeDisplay: true, //当前以播放时间
							fullscreenToggle: true, //全屏按钮
							pictureInPictureToggle: false, //画中画
						}
					},
					function() {
						this.on('error', function(err) { //请求数据时遇到错误
							console.log("请求数据时遇到错误", err)
						});
						this.on('stalled', function(stalled) { //网速失速
							console.log("网速失速", stalled)
						});
					}
				);

			},
			isplay(res){
				console.log('res',res)
			},
			init() {
				this.getCurtime()
				let data = {
					uid: uni.getStorageSync("uid"),
					vtoken: uni.getStorageSync("vtoken"),
					did: this.curid
				}
				this.$Loading()
				if(this.status){
					getVideoUrl(data).then((res) => {
						if (!res) {
							this.$Toast("設備已離線");
						} else {
							this.playInfo = res.data
							// this.videoUrl = res.data.ws_flv
							this.videoUrl = res.data.flv
							this.showVideo = true
							if (res.vtoken) {
								uni.setStorageSync('vtoken', res.vtoken)
							}
							this.playVideo();
							// this.initVideo()
						}
					
					}).catch((err) => {
						console.log('err', err)
						this.$Toast(err.msg)
						setTimeout(() => {
							// this.goBack()
						}, 1200)
					}).finally(() => {
						uni.hideLoading()
					})
				}
				
				//get caseuser 31

				getCaseUserIdent({
					uid: uni.getStorageSync("uid"),
					did: this.curid,
					caseid: this.caseid
					// caseid:30,
					// did:"34020000001110005555",
				}).then((res) => {
					this.curUserident = res.ident
					// if(this.curUserident == 1){
					this.$nextTick(() => {
						this.reload()
					})

					// }
				}).catch(() => {
					this.curUserident = 0
				})

				//测试用
				// this.playVideo();
			},
			setBtnBoxHeight() {
				// const videoElement = this.$refs.videoPlayer.$el;
				// const btnboxElement = this.$el.querySelector('.videobox .btnbox');
				// this.videoHeight = videoElement.clientHeight;
				// btnboxElement.style.height = this.videoHeight + 'px';
			},
			scrollChild(scrollDistance) {
				this.isfull = scrollDistance == 0 ? false : true
				uni.pageScrollTo({
					scrollTop: scrollDistance,
					duration: 0,
					selector: '.content'
				});
			},
			changeFulls(e){
				this.isfull = e
			},
			saveScreen(file) {
				this.uploadFile(file)
			},
			uploadFile(blob) {
				let _this = this
				_this.$Loading()
				const formData = new FormData();
				formData.append('file', blob, new Date().getTime()+'.png'); // 你可以自定义文件名
				formData.append('uid', uni.getStorageSync('uid'))
				const xhr = new XMLHttpRequest();
				xhr.open('POST', this.action, true);
				xhr.setRequestHeader('token', uni.getStorageSync('userToken'));
				xhr.send(formData);

				xhr.onload = function() {
					if (xhr.status === 200) {
						
						let result = JSON.parse(xhr.responseText)
						if(result.data.code==102){
							_this.$Toast('請重新登錄')
							setTimeout(()=>{
								_this.toPage("Home")
							},1200)
							return;
						}
						let imgUrl = result.data.url
						//將圖片保存到對應的圖集
						_this.saveImg(imgUrl)
					} else {
						_this.$Toast('截圖失敗');
					}
				};

				xhr.onerror = function() {
					_this.$Toast('截圖失敗');
				};
			},
			saveImg(img){
				let data = {
					uid:uni.getStorageSync('uid'),
					img,
					caseid:this.caseid,
					did:this.curid,
					time: parseInt((new Date().getTime())/1000) 
				}
				saveVideoPic(data).then((res)=>{
					this.$Toast('截圖成功');
				}).catch((err)=>{
					this.$Toast('截圖失敗');
				}).finally(()=>{
					uni.hideLoading()
				})
			},
			getCurtime() {
				let date = new Date();
				let year = date.getFullYear(), //年
					month = date.getMonth() + 1, //月
					day = date.getDate(), //日
					days = date.getDay();
				month = month < 10 ? '0' + month : month;
				day = day < 10 ? '0' + day : day;
				this.curtimestamp = parseInt(date.getTime() / 1000)
				this.timePickerDefault = this.formatTimestamp(this.curtimestamp)
			},
			formatTimestamp(timestamp) {
				let date = new Date(timestamp * 1000);
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				let hours = date.getHours();
				let minutes = date.getMinutes();
				let seconds = date.getSeconds();

				month = month < 10 ? '0' + month : month;
				day = day < 10 ? '0' + day : day;
				hours = hours < 10 ? '0' + hours : hours;
				minutes = minutes < 10 ? '0' + minutes : minutes;
				seconds = seconds < 10 ? '0' + seconds : seconds;

				let formattedDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
				return formattedDate;
			},
			playVideo() {
				// console.log("22")
				// this.videoObj.$refs.video.addEventListener('play', this.onVideoPlay);
				// this.videoObj.$refs.video.addEventListener('ended', this.onVideoEnded);
				// this.videoObj.$refs.video.addEventListener('pause', this.onVideoPause);
				// this.videoObj.$refs.video.addEventListener('timeupdate', this.onVideoTimeUpdate);
				// // if (this.videoObj && this.videoObj.src) {
				// console.log('开始播放')
				// this.videoObj.play();
				// }
			},
			onVideoTimeUpdate() {
				console.log('当前时间:', this.videoObj.$refs.video.currentTime);
				// console.log('播放状态:', this.videoObj.$refs.video.paused ? '暂停' : '播放中');
			},
			onVideoPlay() {
				console.log('播放中');
				this.showLoading = false
			},
			onVideoEnded() {
				this.$Toast("該設備已離線")
				setTimeout(() => {
					this.goBack()
				}, 1200)
			},
			onVideoPause() {
				// console.log('暂停');
			},
			videoload() {
				// console.log('loading')
				// this.showLoading = true
			},
			openAuthor() {
				this.isaction = !this.isaction
			},
			changeMuted() {
				this.ismuted = !this.ismuted
				if (!this.ismuted) {
					this.videoObj.$refs.video.muted = false
				} else {
					this.videoObj.$refs.video.muted = true
				}
			},
			toFullScreen() {
				this.isfull = !this.isfull
				this.$el.querySelector('.loading').style.height = '0px'
				if (this.isfull) {
					this.$el.querySelector('.loading').style.height = '100vh'
				} else {
					this.setBtnBoxHeight()
				}
			},
			confirmDate(e) {
				this.startTime = e.timestamp
				this.showEndTime = true
			},
			confirmDateEnd(e) {
				this.endTime = e.timestamp
				let data = {
					// app: this.playInfo.app,
					// stream: this.playInfo.stream,
					app:"live",
					stream:this.curid,
					startTime: this.startTime,
					endTime: this.endTime
				}
				this.toPage('Playbacklist', data)
			},
			reload() {
				this.$refs.paging.reload();
			},
			queryList(pageNo, pageSize) {
				const data = {
					page: pageNo,
					pageSize,
					uid: uni.getStorageSync("uid"),
					did: this.curid,
					caseid: this.caseid
					// caseid:30,
					// did:"34020000001110005555",
				}
				if (pageNo == 1) {
					this.templist = []
				}
				getCaseUserlist(data).then((res) => {
					this.curUserident = res.user_auth
					this.templist = this.templist.concat(res.list)
					this.$refs.paging.complete(res.list)
				}).catch((err) => {
					this.$Toast(err.msg)
				})

			},
			openShowStarttime() {
				this.showTime = true
			},
			getAuthTxt(n) {
				switch (n) {
					case 1:
						return '管理層';
						break;
					case 2:
						return '設計師';
						break;
					default:
						return '客戶'
				}
			},
			toPics(){
				this.toPage('Pics',{caseid:this.caseid,did:this.curid})
			},
			changeCheckbox(i) {
				// console.log(this.userlist[i])
			},
			toUpdateAuth() {
				let selectList = this.templist.filter(item => item.ischecked == true)
				if (selectList.length == 0) {
					this.$Toast("請選擇用戶")
					return;
				}
				let select_arr = [];
				selectList.map((item) => {
					select_arr.push(item['mid'])
				});
				let select_str = select_arr.join(",")
				let data = {
					uid: uni.getStorageSync("uid"),
					did: this.curid,
					caseid: this.caseid,
					uids: select_str
				}
				this.$Loading()
				updateAuth(data).then((res) => {
					this.$Toast(res.msg)
				}).catch((err) => {
					this.$Toast(err.msg)
				}).finally(() => {
					this.isaction = false
					this.reload()
					uni.hideLoading()
				})
			},
			toPlayback() {
				// console.log(this.playInfo)
				let data = {
					// app: this.playInfo.app,
					// stream: this.playInfo.stream,
					app:"live",
					stream:this.curid,
					caseid: this.caseid,
					did: this.curid,
				}
				this.toPage('Playbacklist', data)
			},
			toPage(name, params = {}) {
				this.$navi({
					route: {
						name,
						params
					},
				})
			},
			goBack() {
				uni.navigateBack(-1)
			}

		}
	}
</script>

<style lang="scss">
	.content{
		min-height: 100vh;
		&.fixed{
			position: fixed;
			top:-44px;
		}
	}
	.main {
		padding-top: 88rpx;

		video {
			width: 100%;
		}

		/deep/ .uni-video-bar,
		/deep/ .uni-video-cover {
			display: none;
		}

		.myvideo {
			width: 100%;
			height: 220px;
		}

		.videobox {
			position: relative;
			height: 220px;
			background-color: #000;
			&.videofull {
				width: 100vw;
				height: 100vh;
				position: fixed;
				top: 0;
				z-index: 99998;
			}

			.time {
				position: absolute;
				left: 10rpx;
				top: 6rpx;
				color: #ccc;
				z-index: 3;
				font-size: 24rpx;
				mix-blend-mode: difference;

				&.timefull {
					position: fixed;
					z-index: 99999;
					top: 20rpx;
					left: 30rpx;
				}
			}

			.btnbox {
				width: 100%;
				position: absolute;
				z-index: 9;
				bottom: 20rpx;
				right: 0rpx;
				display: flex;
				align-items: flex-end;
				justify-content: flex-end;
				display: none;

				&.btnboxfull {
					z-index: 99999;
					height: 100vh !important;
					bottom: 0;

					.sound {
						position: absolute;
						bottom: 12rpx;
						margin-right: 60rpx;
					}

					.fullbtn {
						top: -20rpx;
					}
				}

				.sound {
					margin-left: auto;
					margin-right: 30rpx;
				}

				.fullbtn {
					mix-blend-mode: difference;
					position: relative;
					top: -6rpx;
					right: 20rpx;
					z-index: 9;
				}

				.loading {
					position: absolute;
					width: 100%;
					height: inherit;
					z-index: 8;
					display: none;

					&.show {
						display: flex;
						justify-content: center;
						align-items: center;

						&.full {
							height: 100vh;
							position: absolute;
							top: 0;
						}
					}

				}
			}

			.full {
				width: 100vw;
				height: 100vh;
				position: fixed;
				z-index: 9998;
				top: 0;
			}
		}

		.actionbox {
			margin-top: 20rpx;

			.box {
				background-color: #f2f2f2;
				padding: 20rpx;
				border-radius: 4rpx;

				.item {
					display: flex;
					width: 50%;
					justify-content: center;
					align-items: center;

					&:first-child {
						width: 25%;
					}

					&:last-child {
						width: 25%;
					}

					.picbox {
						margin-bottom: 4rpx;
					}
				}
			}
		}

		.userlist {
			.titbox {
				.title {
					position: relative;
					padding-left: 16rpx;

					&::before {
						content: "";
						width: 6rpx;
						height: 28rpx;
						background-color: #007aff;
						display: inline-block;
						box-shadow: 1px 1px 3px #0964c7;
						position: absolute;
						top: 4rpx;
						left: 0;
					}
				}

				.subtitle {
					font-size: 26rpx;
					background-color: #f2f2f2;
					padding: 6rpx 20rpx;
					border-radius: 8rpx;

					&.on {
						background-color: #007aff;
						color: #fff;
					}
				}
			}

			.useritembox {
				margin-top: 20rpx;

				.item {
					background-color: #f9f9f9;
					padding: 20rpx 30rpx;
					margin-bottom: 10rpx;
					border-radius: 4rpx;

					.left {
						.namebox {
							justify-content: flex-start;
							margin-bottom: 4rpx;

							.name {}
						}
					}

					.right {
						flex-shrink: 0;
						display: flex;
						justify-content: flex-end;
						align-items: flex-end;

						.checkbox {
							width: 36rpx;
						}

					}
				}
			}
		}

	}

	.btnbox {
		position: fixed;
		bottom: 120rpx;
		width: 100%;
		margin: 0 auto;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999999;

		.btn {
			width: 240rpx;
			height: 64rpx;
			background-color: #007aff;
			color: #fff;
			border-radius: 8rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
</style>